package Set;

import java.util.*;

/*
 * 2014-9-1
 * HashSet 不重覆相同的物件
 */

public class HashSetTest {
	public static void main(String[] args) {
		Set<Student> set = new HashSet<Student>();
		set.add(new Student("Justin", "B835031"));
		set.add(new Student("Monica", "B835032"));
		set.add(new Student("Justin", "B835031"));
		System.out.println(set);
	}
}

class Student {
    private String name;
    private String number;
    Student(String name, String number) {
        this.name = name;
        this.number = number;
    }

   // NetBeans自動產生的equals()與hashCode()
    // 就示範而言已經足夠了

    @Override
    public int hashCode() {
       // Objects 有 hash() 方法可以使用
       // 以下可以簡化為 return Objects.hash(name, number);
        int hash = 7;
        hash = 47 * hash + Objects.hashCode(this.name);
        hash = 47 * hash + Objects.hashCode(this.number);
        System.out.println(hash);
        return hash;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final Student other = (Student) obj;
        if (!Objects.equals(this.name, other.name)) {
            return false;
        }
        if (!Objects.equals(this.number, other.number)) {
            return false;
        }
        return true;
    }
    
    @Override
    public String toString()  {
        return String.format("(%s, %s)", name, number);
    }
}

